package com.addcn.caruimodule.button;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import com.addcn.caruimodule.R;

/**
 * Created by 10528 on 2016/4/29.
 */
public class ButtonGroupView extends LinearLayout{
    private int mNumPerLine;
    private int mSpacing;
    private int mItemHeight;
    private Context mContext;
    public ButtonGroupView(Context context) {
        this(context,null);
    }

    public ButtonGroupView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a=context.getTheme().obtainStyledAttributes(
                attrs, R.styleable.ButtonGroupView,0,0);
        mContext=context;
        mNumPerLine=a.getInteger(R.styleable.ButtonGroupView_numPerLine,0);
        mSpacing=(int)a.getDimension(R.styleable.ButtonGroupView_spacing,0);
        mItemHeight=(int)a.getDimension(R.styleable.ButtonGroupView_itemHeight,0);
    }

    public void setViews(View[] views){
        if(views==null||views.length==0){
            return;
        }
        View[] copy;
        if(views.length%mNumPerLine!=0){
            copy=new View[views.length+mNumPerLine-views.length%mNumPerLine];
            System.arraycopy(views,0,copy,0,views.length);
            for(int i=views.length;i<copy.length;i++){
                copy[i]=new View(mContext);
                LayoutParams lp=new LayoutParams(0,
                        LayoutParams.WRAP_CONTENT,
                        1.0f);
                copy[i].setLayoutParams(lp);
            }
        }else{
            copy=views;
        }

        LinearLayout layout=new LinearLayout(mContext);
        layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                mItemHeight));
        layout.setOrientation(HORIZONTAL);
        addView(layout);

        LayoutParams lp=new LayoutParams(0,
                LayoutParams.MATCH_PARENT,1.0f);
        for(int i=0;i<copy.length;i++){
            copy[i].setLayoutParams(lp);
            layout.addView(copy[i]);
            //間隔
            if((i+1)%mNumPerLine!=0){
                View v=new View(mContext);
                v.setLayoutParams(new LayoutParams(mSpacing,LayoutParams.WRAP_CONTENT));
                layout.addView(v);
            }

            if((i<copy.length-1)&&(i+1)%mNumPerLine==0){
                layout=new LinearLayout(mContext);
                LayoutParams layoutParams=new LayoutParams(LayoutParams.MATCH_PARENT,
                        mItemHeight);
                layoutParams.setMargins(0,mSpacing,0,0);
                layout.setLayoutParams(layoutParams);
                layout.setOrientation(HORIZONTAL);
                addView(layout);
            }
        }
    }
}
